package com.workcell.workdata.xthings.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.workcell.workdata.common.core.util.R;
import com.workcell.workdata.xthings.dto.ChatReturnData;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

//@RestController
//@RequiredArgsConstructor
//@RequestMapping("/ChatGPT" )
//@Api(value = "ChatGPT", tags = "ChatGPT")
public class ChatGPTController {


    @PostMapping("/chat")
    public R chat(@PathVariable String prompt) throws IOException {

         String BASE_URL = "https://api.openai.com/v1/chat/completions";

         String API_KEY = "Bearer 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";

         prompt = "你好";

        String json = "{\"model\":\"gpt-3.5-turbo\",\"max_tokens\":4000,\"temperature\":0.5,\"top_p\":1,\"frequency_penalty\":0.0,\"presence_penalty\":0.0,\"messages\":[{\"role\":\"user\",\"content\":\""+ prompt +"\"}]}";

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        // 拼接参数
        //跳ssl验证
        OkHttpClient client2 = getUnsafeOkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
        //证书过期，不跳证书验证版
        //OkHttpClient client2 = client.newBuilder().readTimeout(60000, TimeUnit.SECONDS).build();
        Request.Builder builder = new Request.Builder().url(BASE_URL).post(body);
        builder.addHeader("Authorization", API_KEY);
        builder.addHeader("Content-Type", "application/json");
        // 发送请求
        Request request = builder.build();
        System.out.println("request"+request);
        Response response = client2.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }

        //获取响应体
        ResponseBody responseBody = response.body();

        System.out.println("response==============="+response.body().string());

        //将json数据返回为java（通过获取json的方式）
        String returnJson = response.body().string();

        JSONObject jsonObject = JSONObject.parseObject(returnJson);
        String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");


        //返回给前段的对象(通过实体类的方式)
        ChatReturnData chatReturnData = JSON.parseObject(returnJson, ChatReturnData.class);

//        JSONObject.toJavaObject(responseBody, );

        return R.ok(content);


    }

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            /**
             * https证书过期，跳过证书验证
             */
            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



}
